<template>
  <el-dialog
    v-model="dialogVisible"
    :title="$t('common.changePhone')"
    width="500px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    :show-close="false"
  >
    <Phone-code
      v-if="dialogVisible"
      ref="phoneCodeRef"
      :send-code-api="SystemApi.sendSmsCode"
      :send-code-scene="SmsSceneEnum.ChangePhone"
      :platform="PLATFORM"
    ></Phone-code>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submit">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ElMessage, FormInstance } from "element-plus";
import { watch, ref } from "vue";
import PhoneCode, { IPhoneCodeFrom } from "@/components/PhoneCode/index.vue";
import { PLATFORM } from "@/config";
import { SystemApi } from "@/api/modules";
import { SmsSceneEnum } from "@/enums/httpEnum";
import { useUserStore } from "@/stores/modules/user";
const phoneFormRef = ref<FormInstance>();
const phoneCodeRef = ref<InstanceType<typeof PhoneCode> | null>(null);
const userStore = useUserStore();
const dialogVisible = ref(false);
watch(dialogVisible, () => {
  phoneFormRef.value?.resetFields();
});

const submit = () => {
  phoneCodeRef.value?.submit().then((data: IPhoneCodeFrom) => {
    const payload = {
      mobilePhone: data.mobile,
      verificationCode: data.validCode,
    };

    SystemApi.userBindPhone(payload).then(res => {
      ElMessage.success("操作成功");
      dialogVisible.value = false;
      userStore.getUserInfo();
    });
  });
};
const openDialog = () => {
  dialogVisible.value = true;
};

defineExpose({ openDialog });
</script>
